package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.GantryMapper;
import com.ruoyi.system.mapper.MaterialLogMapper;
import com.ruoyi.system.mapper.MaterialMapper;
import com.ruoyi.system.mapper.TProjectAimMapper;
import com.ruoyi.system.service.MaterialLogService;
import com.ruoyi.system.service.MaterialService;
import lombok.var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.List;
import java.util.Random;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_PATTERN;

@Service
public class MaterialLogServiceImpl extends ServiceImpl<MaterialLogMapper, MaterialLogEntity> implements MaterialLogService {

    @Autowired
    private MaterialLogMapper materialLogMapper;


    private static final Logger logger = LoggerFactory.getLogger(Threads.class);


    @Autowired
    private MaterialService materialService;


    @Autowired
    private MaterialCommonImpl commonMaterialService;



    /*
    *  出库按照天统计
    * */
    public List<MaterialLogStatisticsEntity> sumNumByDateAndName(String beginTimeFormat, String endTimeFormat) {
        return materialLogMapper.sumNumByDateAndName(beginTimeFormat, endTimeFormat);
    }


    public boolean addMaterialLog( MaterialLogEntity params) {

        var isIn = true;
        // 2 是出库
        if (params.getIsIn() == 2) {
            isIn = false;
        }

        if (params.getMaterialCode() == null) {
            params.setMaterialCode(commonMaterialService.createMaterialCode(isIn));
        }

        // 更新 库存记录 不存在就添加 存在就更新
        this.upsertMaterialLog(params);

        logger.info("add material_code id:{}, sync_id: {}", params.getId(), params.getSyncId());
        var newMaterialEntity = convert2MaterialEntity(params);

        var materialCountEntity = materialLogMapper.getMaterialCount(newMaterialEntity.getMaterialCode());

        float newMaterialCount = 0.0F;

        if (materialCountEntity != null) {
            newMaterialCount = materialCountEntity.getTotalCount();
        }

        if (newMaterialCount <= 0.0) {
            newMaterialCount = 0.0F;
        }
        newMaterialEntity.setActualCount(newMaterialCount);
        return materialService.upsertMaterial(newMaterialEntity); // 在更新库存量
    }


    /*
    *  如果 材料入库记录 ||  id 存在 就尝试获取一个记录, 记录存在就更新, 不存在就插入
    * */

    @Transactional
    public boolean upsertMaterialLog( MaterialLogEntity params) {

        if (params.getMaterialCode() == null) {
            params.setMaterialCode(commonMaterialService.createMaterialCode(params.getIsIn() == 1));
        }
        var existWrap = new LambdaQueryWrapper<MaterialLogEntity>();

        existWrap.eq(MaterialLogEntity::getDelFlag,0);

        boolean needQuery = false;

        if (params.getId() != null  && !params.getId().isEmpty() && !params.getId().equals("0")) {
            existWrap.eq(MaterialLogEntity::getId,params.getId());
            needQuery = true;
        }

        if (params.getSyncId() != null && params.getSyncId() != 0 ) {
            existWrap.eq(MaterialLogEntity::getSyncId, params.getSyncId());

            needQuery = true;
        }

        if (!needQuery) {
            return saveOrUpdate(params);
        }
        var existMaterialLog = getOne(existWrap);
        if( existMaterialLog != null) {
            params.setId(existMaterialLog.getId());
            return saveOrUpdate(params);
        }

        return saveOrUpdate(params);
    }


    /*
     *  从 materialLog 记录中提取出 materialEntity
     * */
    public MaterialEntity convert2MaterialEntity(@RequestBody MaterialLogEntity params) {
        var ans = new MaterialEntity();

        BeanUtils.copyProperties(params, ans);


        ans.setId(null); // 清空 id 字段

        return ans;
    }

    /*
    * 删除 进库或者出库记录
    * */

    @Override
    public boolean deleteMaterialLog(String materialLogId) {
        var existWrap = new LambdaQueryWrapper<MaterialLogEntity>();
        existWrap.eq(MaterialLogEntity::getDelFlag,0);

        if (materialLogId != null  && !materialLogId.isEmpty() && !materialLogId.equals("0")) {
            existWrap.eq(MaterialLogEntity::getId, materialLogId);
        }
        var existMaterialLog = getOne(existWrap);
        if( existMaterialLog == null) {
            logger.info("delete material log error record not exist {}", materialLogId);
            return false;
        }
        existMaterialLog.setDelFlag(1);
        return addMaterialLog(existMaterialLog);

    }

    @Override
    public Integer countMaterialInNum(String materialCode) {

        String materialCodePattern = "%" + materialCode + "%";
        return materialLogMapper.countMaterialInNum(materialCodePattern);
    }



}
